package cn.tanghom.app.baiding.controller.api;

import cn.tanghom.app.system.model.Organization;
import cn.tanghom.app.system.model.User;
import cn.tanghom.app.system.service.OrganizationService;
import cn.tanghom.app.system.service.UserService;
import cn.tanghom.support.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户相关接口
 *
 * @author tanghom
 */
@Controller
@RequestMapping("/api/user")
@Api(description = "用户相关接口")
public class UserApiController {

    @Resource
    private UserService userService;
    @Resource
    private OrganizationService organizationService;
    /**
     * 登录
     *
     * @param loginName 帐号
     * @param loginPwd  密码
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation(value = "登录", notes = "登录", produces = "application/json")
    @ResponseBody
    public String login(@ApiParam(name = "loginName", value = "帐号", required = true) @RequestParam String loginName,
                        @ApiParam(name = "loginPwd", value = "密码", required = true) @RequestParam String loginPwd, HttpServletRequest request) {
        try {
            User user = userService.findByLoginName(loginName);
            if (null != user) {
                if (0 == user.getStatus()) {
                    return CommonUtils.msgCallback(false, "登录失败，帐号锁定", null); // 帐号锁定
                }
                if (2 == user.getStatus()) {
                    return CommonUtils.msgCallback(false, "登录失败，帐号待审核", null); // 帐号待审核
                }
                String loginPwdDb = user.getLoginPwd();
                loginPwd = Md5Util.encrypt(loginPwd);
                if (!loginPwd.equals(loginPwdDb)) {
                    return CommonUtils.msgCallback(false, "登录失败，密码错误", null); // 密码不正确
                }
                // 当验证都通过后，把用户信息放在session里
                HttpSession httpSession = request.getSession();
                String sessionId = httpSession.getId();
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("sessionId", JsonUtil.toJSONString(sessionId));
                map.put("user", JsonUtil.toJSONString(user));
                String returnJson = JsonUtil.toJSONString(map);
                return CommonUtils.msgCallback(true, "登录成功", returnJson);
            } else {
                return CommonUtils.msgCallback(false, "登录失败，请重试！", null);
            }
        } catch (Exception e) {
            return CommonUtils.msgCallback(false, "登录失败，请重试！", null);
        }
    }

    /**
     * 用户注册
     *
     * @param loginName 帐号
     * @param loginPwd  密码
     * @param smsCode   密码
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ApiOperation(value = "用户注册", notes = "用户注册")
    @ResponseBody
    public String register(@ApiParam(name = "loginName", value = "帐号（手机号）", required = true) @RequestParam String loginName,
                           @ApiParam(name = "loginPwd", value = "密码", required = true) @RequestParam String loginPwd,
                           @ApiParam(name = "smsCode", value = "短信验证码", required = true) @RequestParam String smsCode,
                           @ApiParam(name = "stationId", value = "消防站ID", required = true) @RequestParam Long stationId,
                           HttpServletRequest request) {
        try {
            if (!Validator.isMobile(loginName)) {
                return CommonUtils.msgCallback(false, "请输入正确的手机号", null);
            }
            if (!Validator.isPassword(loginPwd)) {
                return CommonUtils.msgCallback(false, "请输入6-16位密码", null);
            }
            if (StringUtils.isNullOrEmpty(smsCode)) {
                return CommonUtils.msgCallback(false, "请输入短信验证码", null);
            }
            if (null ==stationId) {
                return CommonUtils.msgCallback(false, "请选择消防站", null);
            }
            HttpSession httpSession = request.getSession();
            Map<String, Object> dataMapSession = (Map<String, Object>) httpSession.getAttribute(loginName);
            //判断是否发送了短信验证码
            if (null == dataMapSession) {
                return CommonUtils.msgCallback(false, "请发送短信验证码！", null);
            }
            //若已发送，判断是否超时
            Date sendTime = (Date) dataMapSession.get("sendTime");
            Integer minutes = DateUtil.minutesBetween(sendTime, new Date());
            if (minutes >= 2) {
                httpSession.removeAttribute(loginName);
                return CommonUtils.msgCallback(false, "短信验证码已失效,请重新发送短信验证码！", null);
            }
            //若未超时，判断验证码是否正确
            String smsCodeSession = (String) dataMapSession.get("smsCode");
            if (!smsCodeSession.equals(smsCode)) {
                return CommonUtils.msgCallback(false, "短信验证码不正确,请重新输入！", null);
            }
            //满足上面条件后进行用户名判断
            User user = userService.findByLoginName(loginName);
            if (null != user) {
                return CommonUtils.msgCallback(false, "当前手机不存在！", null);
            }
            User newUser = new User();
            newUser.setLoginName(loginName);
            newUser.setLoginPwd(loginPwd);
            newUser.setUserName(loginName);
            newUser.setPhone(loginName);
            Organization organization =organizationService.findById(stationId);
            newUser.setOrganizationId(stationId);
            newUser.setOrganizationName(organization.getName());
            newUser.setStatus(2);
            userService.reg(newUser);
            httpSession.removeAttribute(loginName);
            return CommonUtils.msgCallback(true, "注册成功，管理员审核账号后即可登录！", null);
        } catch (Exception e) {
            return CommonUtils.msgCallback(false, "注册失败，请重试！", null);
        }
    }

    /**
     * 修改密码
     *
     * @param loginName 帐号
     * @param loginPwd  密码
     * @param smsCode   短信
     * @return
     */
    @RequestMapping(value = "/find_pwd", method = RequestMethod.POST)
    @ApiOperation(value = "修改密码  ", notes = "修改密码")
    @ResponseBody
    public String findPwd(@ApiParam(name = "loginName", value = "帐号（手机号）", required = true) @RequestParam String loginName,
                           @ApiParam(name = "loginPwd", value = "密码", required = true) @RequestParam String loginPwd,
                           @ApiParam(name = "smsCode", value = "短信验证码", required = true) @RequestParam String smsCode,
                           HttpServletRequest request) {
        try {
            if (!Validator.isMobile(loginName)) {
                return CommonUtils.msgCallback(false, "请输入正确的手机号", null);
            }
            if (!Validator.isPassword(loginPwd)) {
                return CommonUtils.msgCallback(false, "请输入6-16位密码", null);
            }
            if (StringUtils.isNullOrEmpty(smsCode)) {
                return CommonUtils.msgCallback(false, "请输入短信验证码", null);
            }
            HttpSession httpSession = request.getSession();
            Map<String, Object> dataMapSession = (Map<String, Object>) httpSession.getAttribute(loginName);
            //判断是否发送了短信验证码
            if (null == dataMapSession) {
                return CommonUtils.msgCallback(false, "请发送短信验证码！", null);
            }
            //若已发送，判断是否超时
            Date sendTime = (Date) dataMapSession.get("sendTime");
            Integer minutes = DateUtil.minutesBetween(sendTime, new Date());
            if (minutes >= 2) {
                httpSession.removeAttribute(loginName);
                return CommonUtils.msgCallback(false, "短信验证码已失效,请重新发送短信验证码！", null);
            }
            //若未超时，判断验证码是否正确
            String smsCodeSession = (String) dataMapSession.get("smsCode");
            if (!smsCodeSession.equals(smsCode)) {
                return CommonUtils.msgCallback(false, "短信验证码不正确,请重新输入！", null);
            }
            //满足上面条件后进行用户名判断
            User user = userService.findByLoginName(loginName);
            if (null == user) {
                return CommonUtils.msgCallback(false, "当前手机不存在！", null);
            }
            user.setLoginPwd(Md5Util.encrypt(loginPwd) );
            userService.update(user);
            httpSession.removeAttribute(loginName);
            return CommonUtils.msgCallback(true, "修改成功", null);
        } catch (Exception e) {
            return CommonUtils.msgCallback(false, "修改失败，请重试！", null);
        }
    }

    /**
     * 发送短信验证码
     *
     * @param mobile 手机号
     * @return
     */
    @RequestMapping(value = "/send_sms", method = RequestMethod.POST)
    @ApiOperation(value = "发送短信验证码", notes = "发送短信验证码")
    @ResponseBody
    public String sendSms(@ApiParam(name = "mobile", value = "手机号", required = true) @RequestParam String mobile, @ApiParam(name = "type", value = "发送类型,1注册,2找回密码", required = true) @RequestParam Integer type, HttpServletRequest request) {
        try {
            if (!Validator.isMobile(mobile)) {
                return CommonUtils.msgCallback(false, "请输入正确的手机号", null);
            }
            HttpSession httpSession = request.getSession();
            Map<String, Object> dataMapSession = (Map<String, Object>) httpSession.getAttribute(mobile);
            if (null != dataMapSession) {
                Date sendTime = (Date) dataMapSession.get("sendTime");
                Integer minutes = DateUtil.minutesBetween(sendTime, new Date());
                if (minutes <= 2) {
                    return CommonUtils.msgCallback(false, "短信验证码发送失败，间隔时间必须大于2分钟！", null);
                }
            }
            String code = "";
            if(1==type){
                code = AliDaYu.reg(mobile);
            }else if(2==type){
                code = AliDaYu.findPwd(mobile);
            }
            if(StringUtils.isNullOrEmpty(code)){
                return CommonUtils.msgCallback(false, "短信验证码发送失败，请重试！", null);
            }
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("mobile", mobile);
            dataMap.put("smsCode", code);
            dataMap.put("sendTime", new Date());
            httpSession.setAttribute(mobile, dataMap);
            return CommonUtils.msgCallback(true, "短信验证码发送成功", JsonUtil.toJSONString(dataMap));
        } catch (Exception e) {
            return CommonUtils.msgCallback(false, "短信验证码发送失败，请重试！", null);
        }
    }

}
